function D=correct_planar_grads_triux(filename,factor)

% correct_planar_grads_triux(filename,factor)
%
% - corrects grad.tra so that Triux Neuromag-306 planar gradiometers are now
% stored with the correct magnitude
%
% MWW 


%% try loading in file

try
    D = spm_eeg_load(filename);
catch
    warning('Unable to run correct_planar_grads on file %s; probably not an MEEG file',filename);
    return;
end

if sum(ismember(unique(D.chantype),'MEGGRAD')) % HL Mod 1.3 - Prevents CTF data being corrected.
    error('Axial Gradiometers Detected! Are you using CTF data? If so you should not be correction gradiometers.')
end

%% correct gradiometer definition;

%1. correct D.sensors
grad = D.sensors('MEG');

%grad.tra(2,2:3)

x=factor*sign(grad.tra);
tmp1=[1:3:size(x,1)];
tmp2=[1:5:size(x,2)];

% set magnetometers back to 1
for i=1:length(tmp1),
    x(tmp1(i),tmp2(i))=1; 
end;

grad.tra=x;

%grad.tra(2,2:3)

D = sensors(D,'MEG',grad);

%2. correct forward models
if isfield(D,'inv');
    for i = 1:length(D.inv);
        %2.1 correct sensors in datareg
        if isfield(D.inv{i},'datareg')
            for j = 1:length(D.inv{i}.datareg)
                
                if strcmp(D.inv{i}.datareg(j).modality,'MEG')
                    disp(['Before correction: tra=']);
                    disp(D.inv{i}.datareg(j).sensors.tra(1:3,1:3));
                    
                    D.inv{i}.datareg(j).sensors.tra = grad.tra;
                    
                    disp(['After correction: tra=']);
                    disp(D.inv{i}.datareg(j).sensors.tra(1:3,1:3));
                end
            end
        end
        
        %2.2 remove previously computed leadfield so that it is recomputed
        %    in future inversions
        if isfield(D.inv{i},'gainmat')
            fname = fullfile(D.path, D.inv{i}.gainmat);
            if exist(fname,'file') %delete the lead field file
                cmd = ['rm ' fname];
                unix(cmd);
            end
            D.inv{i} = rmfield(D.inv{i},'gainmat'); %remove the reference to it
        end
    end
end

save(D);
fprintf('Successfully corrected %s \n',filename);
                    


    